﻿using Microsoft.AspNetCore.Mvc;
using ZR.DataCollection.Model;
using ZR.DataCollection.SingleParameter;
using ZR.Service.IService.ProductionControl;

namespace ZR.Admin.WebApi.Controllers.Business.ProductionControl
{
    /// <summary>
    /// 通讯配置
    /// </summary>
    [AllowAnonymous]
    [Route("ProductionControl/Device")]
    [ApiExplorerSettings(GroupName = "business")]
    public class DeviceController : BaseController
    {
        private readonly ICommunicationConfigService _commAddressService;

        public DeviceController(ICommunicationConfigService commAddressService)
        {
            _commAddressService = commAddressService;
        }

        /// <summary>
        /// 更新通讯配置点位
        /// </summary>
        /// <param name="stationCode">工位代号</param>
        /// <returns></returns>
        [HttpGet("success")]
        public IActionResult ChangePointListening(string stationCode)
        {
            string lineCode = CurrentOPInfo.Current.WorkStationConfig.Find(f => f.WorkstationCode.Equals(stationCode)).ProductionLineCode;
            var commAddressByDb = _commAddressService
                                .QueryByOpAndLine(stationCode, lineCode);
            List<CommPoint> commAddress = commAddressByDb
                                .Select(ca => new CommPoint()
                                {
                                    ItemNo = ca.ItemNo,
                                    ItemAddress = ca.ItemAddress,
                                    ItemType = ca.ItemDataType,
                                    SubItem = ca.SubscribeState,
                                    BlockAddress = ca.BlockAddress,
                                    BlockLength = ca.BlockLength
                                }).ToList();
            Dictionary<int, int> keyValues = new Dictionary<int, int>();
            foreach (var item in commAddressByDb.DistinctBy(d => d.BlockAddress))
            {
                keyValues.Add(item.BlockAddress, item.BlockLength);
            }
            if (!CurrentAppInfo.Current.communicationPairs.Any())
            {
                return SUCCESS("参数为空");
            }

            CurrentAppInfo.Current.communicationPairs[stationCode].ConnectionSubPonit(commAddress, keyValues);
            CurrentAppInfo.Current.communicationPairs[stationCode].Start();
            return SUCCESS("改变成功");
        }
    }
}